package cn.lut.mvc.handler;

import cn.lut.entity.Auth;
import cn.lut.entity.Role;
import cn.lut.service.api.AdminService;
import cn.lut.service.api.AuthService;
import cn.lut.service.api.RoleService;
import cn.lut.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @user:dell
 * @date:2020年11月23 16:01
 */
@Controller
public class AssignHandler {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AuthService authService;
    @ResponseBody
    @RequestMapping(value = "/assign/do/role/assign/auth.json")
    public ResultEntity<String> saveRoleAuthRelationship(
            @RequestBody Map<String,List<Integer>> map
    ){
        authService.saveRoleAuthRelationship(map);
        return ResultEntity.successWithOutData();
    }
    @ResponseBody
    @RequestMapping(value = "/assgin/get/assigned/auth/id/by/role/id.json")
    public ResultEntity<List<Integer>> getAssignedAuthByRoleId(
            @RequestParam("roleId") Integer roleId
    ){
        List<Integer> authIdList= authService.getAssignedAuthIdByRoleId(roleId);
        return ResultEntity.successWithData(authIdList);
    }
    @ResponseBody
    @RequestMapping(value = "/assgin/get/all/auth.json")
    public ResultEntity<List<Auth>> getAllAuth(){
        List<Auth> authList= authService.getAll();
        return ResultEntity.successWithData(authList);
    }



    @RequestMapping(value = "/assign/do/role/assign.html")
    public String saveAdminRoleRelationship(
            @RequestParam("adminId") Integer adminId,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("keyword") String keyword,
            // 我们允许用户在页面上取消所有已分配角色再提交表单，所以可以不提供 roleIdList 请求参
            // 设置 required=false 表示这个请求参数不是必须的
            @RequestParam(value="roleIdList", required=false) List<Integer> roleIdList ) {
        adminService.saveAdminRoleRelationship(adminId,roleIdList);
        return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword;
    }

    @RequestMapping(value = "/assign/to/assign/role/page.html")
    public String toAssignRolePage(@RequestParam("adminId") Integer adminId, ModelMap modelMap){
        // 1.查询已分配的橘色
        List<Role> assignedRoles = roleService.getAssignedRole(adminId);

        // 2.查询未分配的角色
        List<Role> unAssignedRoles = roleService.getUnAssignedRole(adminId);

        modelMap.addAttribute("assignedRoles", assignedRoles);
        modelMap.addAttribute("unAssignedRoles", unAssignedRoles);
        return "assign-role";
    }
}

